import { PoloContext } from "@marvintau/poloscope";
import React, { useState, forwardRef, useContext } from "react";
import Cell from '../Cell';
import EditCell from "../EditCell";

import './row.css'

function prop(object, propPath='') {
  const path = propPath.split('.').reverse();

  let curr = object;
  while(curr && path.length > 0) {
    curr = curr?.[path.pop()];
  }

  return curr;
}

const makeRow = ({cols, select, sticky, disabled, updateProp, editMethods={}}) => forwardRef(({data, index, style}, ref) => {

  const [editing, setEditing] = useState(false);

  const {refreshItem} = useContext(PoloContext);

  const wrappedEditMethods = Object.fromEntries(Object.entries(editMethods)
    .map(([name, method]) => {return [
      name, (index) => {
        method(index);
        refreshItem(index);
      }
    ]}));

  const itemData = data[index] ?? {};

  const colsElem = Object.entries(cols).map(([key, {width, editControl, attr={}}]) => {

    if (editControl) {

      const colProps = {
        key,
        rowIndex: index,
        width,
        editing,
        editDisabled: disabled,
        toggleEditing: () => setEditing(!editing),
      };

      Object.assign(colProps, wrappedEditMethods);

      return <EditCell {...colProps} />
      
    } else {

      const colProps = {
        key,
        rowIndex: index,
        colKey:key,
        children: prop(itemData, key),
        width,
        editing,
        updateProp,
        attr,
      };
    
      return <Cell {...colProps} />
    }
  })
  
  const className = `list-row ${sticky ? 'sticky' : ''} row-${itemData.attr?.style ?? 'norm'}`;
  
  const onClick = (e) => {
    e.preventDefault();
    e.stopPropagation();
    
    if (!editing) {
      select(itemData);
    }
  };
  
  return <div style={style}>
    <div {...{className, ref, onClick}}>
      {colsElem}
    </div>
  </div>
})

export default makeRow;